package com.bst.bsj.bops.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSON;
import com.bst.bsj.base.controller.HttpResponse;
import com.bst.bsj.base.controller.HttpResponse.StatusCode;
import com.bst.bsj.base.controller.WebBaseController;
import com.bst.bsj.bops.BopsConstants;
import com.bst.bsj.bops.MenuConstants;
import com.bst.bsj.bops.web.biz.MerchantRoleService;
import com.bst.bsj.bops.web.biz.RoleResourceService;
import com.bst.bsj.bops.web.biz.SeedlingNamesConfigAndTypeRelationService;
import com.bst.bsj.bops.web.biz.SeedlingNamesConfigService;
import com.bst.bsj.bops.web.biz.SeedlingTypeService;
import com.bst.bsj.bops.web.biz.SystemService;
import com.bst.bsj.bops.web.biz.UserService;
import com.bst.bsj.common.dal.daointerface.SeedlingNamesConfigAndTypeRelationDAO;
import com.bst.bsj.common.dal.dataobject.Merchant;
import com.bst.bsj.common.dal.dataobject.MerchantRole;
import com.bst.bsj.common.dal.dataobject.RoleResource;
import com.bst.bsj.common.dal.dataobject.SeedlingNamesConfig;
import com.bst.bsj.common.dal.dataobject.SeedlingNamesConfigAndTypeRelation;
import com.bst.bsj.common.dal.dataobject.SeedlingType;
import com.bst.bsj.common.dal.dataobject.User;
import com.bst.bsj.portal.util.AuthUtil;
import com.bst.bsj.portal.util.DESPlus;
import com.bst.bsj.portal.util.Pinyin;
import com.homewaimai.common.lang.Result;
import com.homewaimai.common.lang.StringUtil;
import com.homewaimai.framework.web.Constants;
import com.homewaimai.framework.web.request.session.LoginUser;

@Scope("prototype")
@Controller
@RequestMapping(value = "/bops")
public class BopsLoginController extends WebBaseController {

  @Autowired
  private SystemService systemService;

  @Autowired
  private MerchantRoleService merchantRoleService;

  @Autowired
  private RoleResourceService roleResourceService;

  @Autowired
  private UserService userService;
  
  @Autowired
  private SeedlingNamesConfigService seedlingNamesConfigService;
  
  @Autowired
  private SeedlingNamesConfigAndTypeRelationService seedlingNamesConfigAndTypeRelationService;
  
  @Autowired
  private SeedlingTypeService seedlingTypeService;
  
  @RequestMapping(value = "/doimport")
  public ModelAndView doimport(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    ModelAndView modelAndView = getBopsModelAndView("null");
    Map<String,String> maps =  readExcel("c:/test.xlsx")  ;
   
    Iterator it=maps.entrySet().iterator();           
    System.out.println( maps.entrySet().size());    
    String key;           
    String value;    
    Map<String,Long> typemaps =  new HashMap<String,Long>();
    List<SeedlingType>  seedlingtypelist = seedlingTypeService.getAll();
    for(SeedlingType seedlingType:seedlingtypelist){
    	typemaps.put(seedlingType.getName(), seedlingType.getId());
    }
    while(it.hasNext()){    
            Map.Entry entry = (Map.Entry)it.next();           
            key=entry.getKey().toString();           
            value=entry.getValue().toString();    
            // 地被,室内@老贯筋,老牛筋,老官草,五瓣花,老贯草,五叶联,破铜钱,老鸹筋,五齿粑,老鸹嘴,鹌子嘴
            String commonnames = value.split("@")[0];
            String types = value.split("@")[1];
            String   searchs = "";
            if(value.split("@").length>2){
             searchs = value.split("@")[2];
            }
          
            SeedlingNamesConfig seedlingNamesConfig = new SeedlingNamesConfig();
            
            seedlingNamesConfig.setBaseName(key);
            seedlingNamesConfig.setBeginLetter(Pinyin.getPinYinHeadChar(key.substring(0, 1)).toUpperCase());
            seedlingNamesConfig.setCommonNames(commonnames);
            seedlingNamesConfig.setSearchKeyWords(searchs);
           
            Long id = seedlingNamesConfigService.insert(seedlingNamesConfig);
            seedlingNamesConfig.setNumber(id.toString());
            seedlingNamesConfigService.update(seedlingNamesConfig);
            
            for(String type : types.split(",")){
            	if(StringUtil.isNotBlank(type)){
            		if(typemaps.get(type) != null){
            			SeedlingNamesConfigAndTypeRelation andTypeRelation = new SeedlingNamesConfigAndTypeRelation();
            			andTypeRelation.setCommonNameNumber(id.toString());
            			andTypeRelation.setSeedlingTypeNumber(typemaps.get(type).toString());
            			seedlingNamesConfigAndTypeRelationService.insert(andTypeRelation);
            		}else{
            			System.out.println(type+"--------------------");
            		}
            	}
            }
            
           // System.out.println(key+"===="+commonnames+"|"+types+"|"+searchs);     
            
    } 
    System.out.println(maps.size());
    return modelAndView;
  }
  public Map<String,String> readExcel(String path)  
	{  
		String replace ="";
		 Map<String,String> maps =  new HashMap<String,String>();
	    try {  
	    	 
	        File excelFile = new File(path);  
	        FileInputStream is = new FileInputStream(excelFile);  
	        Workbook workbook = WorkbookFactory.create(is); 
	        int sheetCount = workbook.getNumberOfSheets();   
	        //遍历每个Sheet  
	        for (int s = 0; s < sheetCount; s++) {  
	            Sheet sheet = workbook.getSheetAt(s);  
	            int rowCount = sheet.getPhysicalNumberOfRows();  
	             
	            for (int r = 0; r < rowCount; r++) {  
	                Row row = sheet.getRow(r);  
	                int cellCount = row.getPhysicalNumberOfCells();  
	                 
	                    String first = "";
	                    String second = "";
	                    String third = "";
	                    String four = "";
	                for (int c = 0; c < cellCount; c++) {  
	                    Cell cell = row.getCell(c);  
	                    int cellType = cell.getCellType();  
	                    String cellValue = null;  
	                    switch(cellType) {  
	                         case Cell.CELL_TYPE_NUMERIC:    
                             cellValue = cell.getStringCellValue();  
                            break;  
	                        case Cell.CELL_TYPE_STRING:    
	                            cellValue = cell.getStringCellValue();  
	                            break;  
	                        
	                        case Cell.CELL_TYPE_BOOLEAN:  
	                            cellValue = String.valueOf(cell.getBooleanCellValue());  
	                            break;  
	                        case Cell.CELL_TYPE_BLANK:  
	                            cellValue = cell.getStringCellValue();  
	                            break;  
	                        case Cell.CELL_TYPE_ERROR:  
	                            cellValue = "错误";  
	                            break;  
	                        case Cell.CELL_TYPE_FORMULA:  
	                            cellValue = "错误";  
	                            break;  
	                        default:  
	                            cellValue = "错误";  
	                    }  
	                    if(c == 0){
	                    	first = cellValue;
	                    }else if(c == 1){
	                    	second = cellValue;
	                    }else if(c == 2){
	                    	third = cellValue;
	                    }else{
	                    	four = cellValue;
	                    }
	                   String namearr = first+","+second;
	                   String search = second+"@"+third+"@"+four;
	                   for(String name:namearr.split(",")){
	                	   if(StringUtil.isNotBlank(name)){
	                		   if(maps.get(name)!=null || StringUtil.isNotBlank(maps.get(name))){
	                			   replace += name +"/"; 
	                		   }
	                		   maps.put(name, search);
	                	   }
	                   }
	                }  
	            }
 	        }  
	  
	    }  
	    catch (Exception e) {  
	        e.printStackTrace();  
	    }
		return maps;  
	  
	    
	} 
  @RequestMapping(value = "/mongosave")
  @ResponseBody
  public void mongosave(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    HttpResponse resp1 = new HttpResponse(StatusCode.OK);
    Map<String, String> map = new HashMap<String, String>();
    map.put("statusCode", "200");

    User user = new User();
    user.setAge(10);
    user.setName("wangxiaojun");
    user.setId("22223123");

    logger.info("save:" + user);

    userService.saveUser(user);

    resp1.setMap(map);
    writeHttpResponse(resp, resp1);
  }

  @RequestMapping(value = "/mongofind")
  @ResponseBody
  public void mongofind(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    HttpResponse resp1 = new HttpResponse(StatusCode.OK);
    Map<String, String> map = new HashMap<String, String>();
    map.put("statusCode", "200");
    String userss = "";
    List<User> users = userService.findUsersByName("wangxiaojun");
    for (User user : users) {
      System.out.println(user);
      userss += user;
    }

    map.put("user", userss.toString());
    resp1.setMap(map);
    writeHttpResponse(resp, resp1);
  }

  @RequestMapping(value = "/login")
  public ModelAndView login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    ModelAndView modelAndView = getBopsModelAndView("login");
    String identity = "";
    String password = "";
    //获取当前站点的所有Cookie
    Cookie[] cookies = req.getCookies();
    for (int i = 0; i < cookies.length; i++) {//对cookies中的数据进行遍历，找到用户名、密码的数据
      if ("identity".equals(cookies[i].getName())) {
        identity = cookies[i].getValue();
        if (StringUtil.isNotBlank(identity)) {
          modelAndView.addObject("identity", identity);
        }
      } else if ("password".equals(cookies[i].getName())) {
        password = cookies[i].getValue();
        if (StringUtil.isNotBlank(password)) {
          try {
            DESPlus desPlus = new DESPlus();
            password = desPlus.decrypt(password);
            modelAndView.addObject("password", password);
          } catch (Exception e) {
          }

        }
      }
    }
    return modelAndView;
  }

  @RequestMapping(value = "/do_ogin", method = RequestMethod.POST)
  public ModelAndView doLogin(String identity, String password, Integer type, String remember,
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    List<String> actionErrors = new ArrayList<String>();
    if (!BopsConstants.LOGIN_TYPE_SETS.contains(type)) {
      actionErrors.add("非法登录方式！");
      ModelAndView mv = getBopsModelAndView("login");
      mv.addObject("actionErrors", actionErrors);
      mv.addAllObjects(getBopsParams(request));

      return mv;
    }
    Result rst = systemService.loginMerchant(identity, password, type);
    if (!rst.isSuccess()) {
      String error = (String) rst.getModels().get("error");
      actionErrors.add(error);
      ModelAndView mv = getBopsModelAndView("login");
      mv.addObject("type", type);
      mv.addObject("actionErrors", actionErrors);
      mv.addAllObjects(getBopsParams(request));
      return mv;
    }

    Merchant merchant = (Merchant) rst.getModels().get("data");
    LoginUser user = new LoginUser();
    user.setLogined(true);
    user.setLoginId(merchant.getId().longValue());
    user.setMemberId(merchant.getId().toString());
    user.setPwd(merchant.getPassword());
    user.setNickName(merchant.getUserName());
    user.setTs(merchant.getName());
    AuthUtil.setAuthToken(request, user);

    request.getSession().setAttribute(Constants.COOKIE_LAST_LOGINID, merchant.getId().toString());
    request.getSession().setAttribute(Constants.COOKIE_LOGINED, "true");
    request.getSession().setAttribute(Constants.COOKIE_SUBSYSTEM, BopsConstants.SUB_SYSTEM);
    request.getSession().setAttribute(Constants.COOKIE_NICKNAME, merchant.getUserName());

    if ("on".equals(remember)) {
      //cookie记住用户名和密码
      //设置Cookie的有效期为30天
      Cookie nameCookie = new Cookie("identity", identity);
      nameCookie.setMaxAge(60 * 60 * 24 * 30);
      response.addCookie(nameCookie);
      nameCookie.setPath("/");
      response.addCookie(nameCookie);

      //加密保存密码cookie
      DESPlus desPlus = new DESPlus();
      password = desPlus.encrypt(password);
      Cookie pwdCookie = new Cookie("password", password);
      pwdCookie.setMaxAge(60 * 60 * 24 * 30);
      response.addCookie(pwdCookie);
      pwdCookie.setPath("/");
      response.addCookie(pwdCookie);

    } else {
      //删除cookie
      Cookie nameCookie = new Cookie("identity", null);
      nameCookie.setMaxAge(0);
      response.addCookie(nameCookie);
      nameCookie.setPath("/");
      response.addCookie(nameCookie);

      Cookie pwdCookie = new Cookie("password", null);
      pwdCookie.setMaxAge(0);
      response.addCookie(pwdCookie);
      pwdCookie.setPath("/");
      response.addCookie(pwdCookie);
    }

    MerchantRole mRole = merchantRoleService.getByUserId(merchant.getId());
    Long roleId = mRole.getRoleId();

    List<Map<String, List<String>>> menuList = new ArrayList<Map<String, List<String>>>();

    List<RoleResource> resourceList = roleResourceService.getResourceByRoleId(roleId);
    List<String> rNameList = new ArrayList<String>();
    for (RoleResource roleResource : resourceList) {
      rNameList.add(roleResource.getResource());
    }

    List<String> urlList = new ArrayList<String>(); //用于权限过滤

    Map<String, String> parentMap = MenuConstants.MENU_PARENT_MAP; //一级菜单

    for (String resource : rNameList) {
      Map<String, List<String>> firstMap = new HashMap<String, List<String>>();

      if (resource.contains("父菜单")) {
        resource = resource.substring(0, resource.length() - 3);
        String mapKey = parentMap.get(resource);
        Map<String, String> subMap = null;
        if ("MENU_ALL_MAP".equals(mapKey)) {
          subMap = MenuConstants.MENU_ALL_MAP; //二级菜单          

        } else if ("MENU_COMPANY_MAP".equals(mapKey)) {
          subMap = MenuConstants.MENU_COMPANY_MAP;

        } else if ("MENU_GOODS_MAP".equals(mapKey)) {
          subMap = MenuConstants.MENU_GOODS_MAP;

        } else if ("MENU_PRIVILEGE_MAP".equals(mapKey)) {
          subMap = MenuConstants.MENU_PRIVILEGE_MAP;

        } else if ("MENU_MAMAGEMENT_MAP".equals(mapKey)) {
          subMap = MenuConstants.MENU_MAMAGEMENT_MAP;

        } else if ("MENU_AREA_MAP".equals(mapKey)) {
          subMap = MenuConstants.MENU_AREA_MAP;
        }

        List<String> secondList = new ArrayList<String>();
        for (String subKey : subMap.keySet()) {
          if (rNameList.contains(subKey)) {
            secondList.add(subKey + "=" + subMap.get(subKey));//子菜单
            urlList.add(subMap.get(subKey));
          }
        }
        firstMap.put(resource, secondList);
        menuList.add(firstMap);
      }
    }
    request.getSession().setAttribute("menuList", JSON.toJSON(menuList));
    request.getSession().setAttribute("urlList", JSON.toJSON(urlList));

    String rUrl = "/bops/sys/base/main.htm";
    ModelAndView mv = new ModelAndView();
    mv.setView(new RedirectView(rUrl));

    return mv;
  }

  @RequestMapping("/logout")
  public ModelAndView logout(HttpServletRequest request) {

    request.getSession().removeAttribute(Constants.COOKIE_LOGIN_USER);
    request.getSession().removeAttribute(Constants.COOKIE_NICKNAME);
    request.getSession().setAttribute(Constants.COOKIE_LOGINED, "false");

    ModelAndView mv = getBopsModelAndView("login");
    mv.addAllObjects(getBopsParams(request));
    return mv;
  }

}
 
